package cn.yangyumanage.http;

import android.os.Handler;
import android.os.Looper;

import androidx.annotation.NonNull;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import cn.yangyumanage.application.DataApplication;
import cn.yangyumanage.callback.HttpCallBack;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Cookie;
import okhttp3.CookieJar;
import okhttp3.HttpUrl;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class HttpClient {

    private static final String tokenHeaderKey = "Authorization";

    //Handler信息 在类被创建的时候创建 创建时处于UI线程中
    public static Handler handler = new Handler(Looper.getMainLooper());

    public static final int PUBLIC = 0;//公开接口
    public static final int ADMIN = 1;//管理员接口

    // 创建一个CookieJar
//    private static final CookieJar cookieJar = new CookieJar() {
//        private final Map<String, List<Cookie>> cookieStore = new HashMap<>();
//
//        @Override
//        public void saveFromResponse(HttpUrl url, @NonNull List<Cookie> cookies) {
//            cookieStore.put(url.host(), cookies);
//        }
//        @NonNull
//        @Override
//        public List<Cookie> loadForRequest(HttpUrl url) {
//            List<Cookie> cookies = cookieStore.get(url.host());
//            return cookies != null ? cookies : new ArrayList<>();
//        }
//    };

    private static OkHttpClient OkHttpConfig() {
        OkHttpClient.Builder okhttpclient = new OkHttpClient.Builder();//Okhttp终端链接
        okhttpclient.callTimeout(5, TimeUnit.MINUTES);//呼叫超时
        okhttpclient.readTimeout(5, TimeUnit.MINUTES);//读取超时
        okhttpclient.writeTimeout(5, TimeUnit.MINUTES);//写入超时
//        okhttpclient.cookieJar(cookieJar);
        return okhttpclient.build();
    }

    //同步GET
    public static void syncGet(String url, HttpCallBack httpCallBack) {
        Request request = new Request.Builder().url(url).build();

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Response response = OkHttpConfig().newCall(request).execute();
                    String responseBody = response.body().string();
                    httpCallBack.onSuccess(responseBody);
                } catch (IOException e) {
                    httpCallBack.onFailure(e);
                }
            }
        }).start();
    }

    //异步GET
    public static void asyncGet(String url, HttpCallBack httpCallBack, int type) {
        Request request;

        if (type == HttpClient.ADMIN) {
            request = new Request.Builder()
                    .url(url)
                    .addHeader(tokenHeaderKey, DataApplication.token)
                    .build();
        } else {
            request = new Request.Builder()
                    .url(url)
                    .build();
        }

        OkHttpConfig().newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                httpCallBack.onFailure(e);
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                httpCallBack.onSuccess(response.body().string());
            }
        });
    }

    //异步Post json or null
    public static void asyncPost(String url, String json, HttpCallBack httpCallBack, int type) {
        MediaType mediaType = MediaType.Companion.parse("application/json;charset=utf-8");
        RequestBody requestBody;
        if (json == null) {
            requestBody = RequestBody.Companion.create("", null);
        } else {
            requestBody = RequestBody.Companion.create(json, mediaType);
        }
        Request request;
        if (type == HttpClient.ADMIN) {
            request = new Request.Builder()
                    .post(requestBody)
                    .url(url)
                    .addHeader(tokenHeaderKey, DataApplication.token)
                    .build();
        } else {
            request = new Request.Builder()
                    .post(requestBody)
                    .url(url)
                    .build();
        }
        OkHttpConfig().newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                httpCallBack.onFailure(e);
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                httpCallBack.onSuccess(response.body().string());
            }
        });
    }

    //异步Put json
    public static void asyncPut(String url, String json, HttpCallBack httpCallBack, int type) {
        MediaType mediaType = MediaType.Companion.parse("application/json;charset=utf-8");
        RequestBody requestBody = RequestBody.Companion.create(json, mediaType);
        Request request;
        if (type == HttpClient.ADMIN) {
            request = new Request.Builder()
                    .put(requestBody)
                    .url(url)
                    .addHeader(tokenHeaderKey, DataApplication.token)
                    .build();
        } else {
            request = new Request.Builder()
                    .put(requestBody)
                    .url(url)
                    .build();
        }
        OkHttpConfig().newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                httpCallBack.onFailure(e);
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                httpCallBack.onSuccess(response.body().string());
            }
        });
    }

    //异步Delete
    public static void asyncDelete(String url, HttpCallBack httpCallBack, int type) {
        Request request;

        if (type == HttpClient.ADMIN) {
            request = new Request.Builder()
                    .delete()
                    .url(url)
                    .addHeader(tokenHeaderKey, DataApplication.token)
                    .build();
        } else {
            request = new Request.Builder()
                    .delete()
                    .url(url)
                    .build();
        }
        OkHttpConfig().newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                httpCallBack.onFailure(e);
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                httpCallBack.onSuccess(response.body().string());
            }
        });
    }
}
